package cn.com.inossem.http;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class NetworkConnectDelete {
	Context context;
	Handler handler;
	int handlerid;

	public NetworkConnectDelete(Context context, String url, Handler handler, int handlerid) {
		this.context = context;
		this.handler = handler;
		this.handlerid = handlerid;
		getData(url);
	}

	private void getData(final String url) {
		final HttpDelete httpDelete = new HttpDelete(url);
		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();
				try {
					final HttpResponse httpResponse = new DefaultHttpClient().execute(httpDelete);
					String result = "";
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = httpResponse.getEntity();
						try {
							result = EntityUtils.toString(entity);
						} catch (Exception e) {
							e.printStackTrace();
						}
						result.replaceAll("\r", "");
					} else {
						System.out.println("result:" + result);
						Toast.makeText(context, result + "连接失败", Toast.LENGTH_LONG).show();
					}
					if (result != null && !result.isEmpty()) {
						try {
							JSONObject jsonObject = new JSONObject(result);
							int flagCode = jsonObject.getInt("flagCode");
							switch (flagCode) {
								case 0:
									String message = jsonObject.getString("message");
									msg.obj = message;
									msg.what = 99;
									handler.sendMessage(msg);
									break;
								case 1:
									msg.obj = result;
									msg.what = handlerid;
									handler.sendMessage(msg);
									break;
								case 2:
									msg.obj = "用户未登录";
									msg.what = 99;
									handler.sendMessage(msg);
									break;
								default:
									message = jsonObject.getString("message");
									msg.obj = message;
									msg.what = 99;
									handler.sendMessage(msg);
									break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
							msg.obj = "返回数据异常";
							msg.what = 99;
							handler.sendMessage(msg);
						}
					} else {
						msg.obj = "空字符串";
						msg.what = 99;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
					msg.obj = "连接失败";
					msg.what = 99;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}
}